import axios from "axios";

//请求类型
const requestTypes = {
  Get: "get",
  Post: "post",
  Put: "put",
  Delete: "delete",
  PATCH: "PATCH",
  Head: "head",
  Options: "options",
  Purge: "purge",
  Link: "link",
  Unlink: "unlink",
};
//响应类型
const responseType = {
  Arraybuffer: "arraybuffer",
  Blob: "blob",
  Document: "document",
  Json: "json",
  Text: "text",
  Stream: "stream",
};

// 初始化：生成实例，应用默认拦截器
const request = function (config) {
  const service = axios.create({
    // 设置最大的连接时长为10秒
    timeout: 1000 * 10,
  });
  service.interceptors.request.use(beforeRequest(config), requestError);
  service.interceptors.response.use(afterResponse(config), responseError);
  // 请求
  return service.request(config);
};
// 请求前
function beforeRequest(config) {
  config.method = config.method || requestTypes.Get;
  if (config.method === requestTypes.Get) {
    //config.params = qs.stringify(config.data);
    config.params = config.data;
  }
  if (config.method === requestTypes.Post || config.method === requestTypes.Put) {
    //config.data = JSON.stringify(data);
  }
  //添加请求头
  config.headers = config.headers || {};
  //config.headers['Content-Type'] = 'application/json';
  return config;
}
// 请求错误
function requestError(error) {
  return Promise.reject(error);
  //return Promise.reject(new Error(error));
}
// 应答后
function afterResponse(response) {
  return response;
}
// 应答错误
function responseError(error) {
  if (error && error.response) {
    switch (error.response.status) {
      case 400:
        error.message = "请求错误";
        break;
      case 401:
        error.message = "未授权，请登录";
        break;
      case 403:
        error.message = "拒绝访问";
        break;
      case 404:
        error.message = `请求地址出错: ${error.response.config.url}`;
        break;
      case 405:
        error.message = `HTTP方法不被允许: ${error.response.config.method}`;
        break;
      case 408:
        error.message = "请求超时";
        break;
      case 500:
        error.message = "服务器内部错误";
        break;
      case 501:
        error.message = "服务未实现";
        break;
      case 502:
        error.message = "网关错误";
        break;
      case 503:
        error.message = "服务不可用";
        break;
      case 504:
        error.message = "网关超时";
        break;
      case 505:
        error.message = "HTTP版本不受支持";
        break;
      default:
        break;
    }
  }
  return Promise.reject(error);
}

export { request, requestTypes, responseType };
